package validate

import (
	"fmt"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"strings"
)

var validate *validator.Validate
var trans ut.Translator

func InitTrans() ut.Translator {
	trans, _ = ut.New(zh.New()).GetTranslator("zh")
	validate = validator.New()
	validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
		name := fld.Tag.Get("label")
		return name
	})
	err := zhTranslations.RegisterDefaultTranslations(validate, trans)
	if err != nil {
		fmt.Println(err)
	}

	return trans
}

func Verify(data interface{}) string {
	err := validate.Struct(data)
	var ret []string
	if err != nil {
		for _, err := range err.(validator.ValidationErrors) {
			ret = append(ret, err.Translate(trans))
		}
	}
	return strings.Join(ret, ";")
}
